package com.cn.pushpall;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Created by chenyuncong on 2019/8/15.
 */
@Slf4j
public class ThreadPullManage {

    //作用拉取队列数据
    private Thread pullThread;
    //把没有抢到锁的任务，重新去抢锁运行
    private Thread selectThread;

    private boolean pullThreadOff;

    private boolean selectThreadOff;

    public ThreadPullManage() {
        init();
    }

    public void init() {
        pullThread = new Thread(new PullRunnable(),"pull_thread");
        selectThread = new Thread(new SelectRunnable(),"select_thread");

        pullThread.start();
        selectThread.start();
    }

    class PullRunnable implements Runnable{
        @Override
        public void run() {
            Task task =null;
            while (true){
                try {
                    task = QueueGather.lbQueue.take();
                    //判断逻辑
                    int lockVal = SimpleLock.lock(task.getId());
                    if(lockVal==1){
                        //获取到锁
//                        log.info("获取到锁，继续业务运行 [{}]  [{}]  [{}]  [{}]",task.getId(),task.getMoney(),task.getOrderNumber(),task.getSignNum());
                        log.info("首次-成功抢到线程池坑位 账号[{}] 订单号[{}] 次数[{}]",task.getId(),task.getOrderNumber(),task.getSignNum());
                        MyThreadPoolExecutor.threadPoolExecutor.submit(new TaskRunnable(task));
                    }else{
                        //进入选取队列
                        log.info("进入轮询队列 [{}] [{}]",task.getId(),task.getOrderNumber());
                        task.setSignNum(task.getSignNum()+1);
                        QueueGather.selectQueue.put(task);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class SelectRunnable implements Runnable{
        @Override
        public void run() {
            while(true){
                try {
                    Task task = QueueGather.selectQueue.take();
                    int lockVal = SimpleLock.lock(task.getId());
                    if(lockVal==1){
                        log.info("轮询-成功抢到线程池坑位 账号[{}] 订单号[{}] 次数[{}]",task.getId(),task.getOrderNumber(),task.getSignNum());
                        MyThreadPoolExecutor.threadPoolExecutor.submit(new TaskRunnable(task));
                    }else{
                        // 获取延时时间
//                        long timeout = TimeUnit.NANOSECONDS.convert(time, unit);
                        Thread.sleep(10);
                        task.setSignNum(task.getSignNum()+1);
                        QueueGather.selectQueue.put(task);

                        log.info("继续轮询 账号[{}] 订单号[{}] 次数[{}]",task.getId(),task.getOrderNumber(),task.getSignNum());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
